<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/**
     * [upload description]
     * @param  [type] $img  [上传文件]
     * @param  [type] $path [保存路径]
     * @return [type]       [成功、失败数据信息]
     */
    function upload($file,$path='img',$originalName=false){
        $path.='/'.date('Ymd');
        try {
            if(validate(['file'=>'filesize:2097152|fileExt:jpg,jpeg,png,gif'])->check(['file'=>$file])){
                $info = \think\facade\Filesystem::disk('public')->putFile($path, $file,
                    function () use ($file,$originalName){
                        if($originalName){
                            $fileName = $file->getOriginalName();
                        }else{
                            $fileName = $file->getOriginalName().date('YmdHis');
                        }
                        return str_replace('.'.$file->getOriginalExtension(),'',$fileName);
                    }
                );
                if($info){
                    $mes['status']=1;
                    $mes['info']=config('filesystem.disks.public.url').$info;
                }else{
                    $mes['status']=0;
                    $mes['info']='上传失败';
                }
            }else{
                $mes=['status'=>0,'info'=>'文件格式错误'];
            }
        } catch (\think\exception\ValidateException $e) {
            $mes['status']=0;
            $mes['info']=$e->getMessage();
        }
        // 自定义文件名
        return $mes;// 上传到本地服务器
    }

    //公共函数
    //获取文件修改时间
    function getfiletime($file, $DataDir) {
        $a = filemtime($DataDir . $file);
        $time = date("Y-m-d H:i:s", $a);
        return $time;
    }

    //获取文件的大小
    function getfilesize($file, $DataDir) {
        $perms = stat($DataDir . $file);
        $size = $perms['size'];
        // 单位自动转换函数
        $kb = 1024;         // Kilobyte
        $mb = 1024 * $kb;   // Megabyte
        $gb = 1024 * $mb;   // Gigabyte
        $tb = 1024 * $gb;   // Terabyte

        if ($size < $kb) {
            return $size . " B";
        } else if ($size < $mb) {
            return round($size / $kb, 2) . " KB";
        } else if ($size < $gb) {
            return round($size / $mb, 2) . " MB";
        } else if ($size < $tb) {
            return round($size / $gb, 2) . " GB";
        } else {
            return round($size / $tb, 2) . " TB";
        }
    }

    function get_ip($type=0){
        $type = $type ? 1 : 0;
        static $ip =  NULL;
        if ($ip !== NULL) return $ip[$type];
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr  =  explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos  =  array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip   =  trim($arr[0]);
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip   =  $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip   =  $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = ip2long($ip);
        $ip  = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }

	function is_mobile($tel){
        if(preg_match("/^1[345678]{1}\d{9}$/",$tel)){
            return true;
        }else{
            return false;
        }
    }

	/**
     * [get_pinyin 汉字转拼音]
     * @param  string $str [description]
     * @return [type]      [description]
     */
	function get_pinyin($str = ''){
		if($str!=''){
			$pytable = unserialize(file_get_contents('./files/hanzi_pinyin/pytable_without_tune.txt'));

			 // “的”和“中”是多音字
			$str_arr = utf8_str_split($str);
			$result = array('');//dump($str);
			foreach($str_arr as $k=>$char){
				//dump($char);
				if(preg_match('/^[\x{4e00}-\x{9fa5}]+$/u',$char)){
					$pinyin = $pytable[$char];//dump($pinyin);
					$temp_result = array();
					foreach($pinyin as $py){
						//dump($py);
						foreach($result as $v){
							if($k==0){
								$temp_result[] = $v.$py.' ';
							}else{
								$temp_result[] = $v.$py;
							}
						}
					}
					$result = $temp_result;
				}else{
					//dump($result);
					foreach($result as $k=>$v){
						$result[$k] .= $char;
					}
				}
			}
			return $result[0];
		}else{
			return false;
		}
	}

	function utf8_str_split($str,$split_len=1){
		if(!preg_match('/^[0-9]+$/', $split_len) || $split_len < 1){
			return FALSE;
		}
		$len = mb_strlen($str, 'UTF-8');
		if ($len <= $split_len){
			return array($str);
		}
		preg_match_all('/.{'.$split_len.'}|[^\x00]{1,'.$split_len.'}$/us', $str, $ar);
		return $ar[0];
	}

	//二维数组排序
	function arr_sort($arr=array(),$file='',$sort=SORT_ASC){
		if(!empty($arr)){
			$data=$arr;
			foreach ($data as $key => $row) {
				$id[]=$row[$file];
			}
			array_multisort($id,$sort,$data);

			return $data;
		}else{
			return $arr;
		}
	}